package com.lpw.dbvideo.login.service;

import com.lpw.dbvideo.config.WeChatConfig;
import com.lpw.dbvideo.user.domain.User;
import com.lpw.dbvideo.user.service.UserService;
import com.lpw.dbvideo.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;

@Service
public class WeChatServiceImpl implements WeChatService {

    @Autowired
    private WeChatConfig weChatConfig;

    @Autowired
    private UserService userService;

    @Override
    public User saveWeChatUser(String code) {
        // 通过appid加上appsecret以及返回来的code，请求 access_token,这里拼接请求路径
        String openAccessTokenUrl = String.format(WeChatConfig.getOpenAccessTokenUrl(),weChatConfig.getWxOpenAppId(),weChatConfig.getWxOpenSecret(),code);
        Map<String, Object> baseMap = HttpUtils.doGet(openAccessTokenUrl);
        if(baseMap == null || baseMap.isEmpty()){
            return null;
        }
        // 获取到的access_token
        String accessToken = baseMap.get("access_token").toString();
        // 授权用户的唯一标识
        String openId = baseMap.get("openid").toString();

        // 获取用户基本信息
        String userInfoUrl = String.format(WeChatConfig.getOpenUserInfoUrl(),accessToken,openId);
        Map<String, Object> baseUserInfo = HttpUtils.doGet(userInfoUrl);
        if(baseUserInfo == null || baseUserInfo.isEmpty()){
            return null;
        }
        String openid = (String) baseUserInfo.get("openid");

        User dbUser = userService.findByOpenId(openId);
        if(dbUser != null){
            return dbUser;
        }
        String nickname = (String) baseUserInfo.get("nickname");
        // 若出现乱码可以通过下面方法进行处理
        try {
            nickname = new String(nickname.getBytes("ISO-8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        Double temSex = (Double) baseUserInfo.get("sex");
        Integer sex = temSex.intValue();
        String headimgurl = (String) baseUserInfo.get("headimgurl");
        String province = (String) baseUserInfo.get("province");
        String city = (String) baseUserInfo.get("city");
        String country = (String) baseUserInfo.get("country");
        String unionid = (String) baseUserInfo.get("unionid");
        StringBuilder stringBuilder = new StringBuilder(country).append("||").append(province).append("||").append(city);
        String finalAddress = stringBuilder.toString();

        User user = new User();
        user.setOpenid(openid);
        user.setName(nickname);
        user.setSex(sex);
        user.setHeadImg(headimgurl);
        user.setCity(finalAddress);
        user.setCreateTime(new Date());
        userService.save(user);
        return user;
    }
}
